package com.aboverock.module.system.databind;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.reflections.ReflectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aboverock.common.enums.UserTypeEnum;
import com.aboverock.module.system.domain.User;
import com.aboverock.module.system.utils.UserInfoUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

/**
 * The Class UserDeserializer.
 *
 * @author Rock Wang
 */
public class UserDeserializer extends JsonDeserializer<User> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public User deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        JsonNode node = p.getCodec().readTree(p);

        User user = new User();
        Class<User> clz = User.class;
        @SuppressWarnings("unchecked")
        Set<Field> fields = ReflectionUtils.getAllFields(clz);
        fields.forEach(field -> {
            try {
                Method method = clz.getMethod("set" + StringUtils.capitalize(field.getName()),
                        field.getType());
                JsonNode value = node.get(field.getName());
                if (value != null && !value.isNull()) {
                    method.invoke(user, convert(value, field.getType()));
                }
            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                    | IllegalArgumentException | InvocationTargetException e) {
                logger.error("Data-Smart：User对象反序列化异常", e);
                throw new RuntimeException(e);
            }
        });

        if (user.getType() != null && UserTypeEnum.LOCAL.getValue() == user.getType()) {
            user.setLoginName(UserInfoUtil.addSuffix2LocalUserLoginName(user.getLoginName()));
        }
        return user;
    }

    private Object convert(JsonNode node, Class<?> clz) {
        if (String.class.equals(clz)) {
            return node.asText();
        } else if (Integer.class.equals(clz)) {
            return node.asInt();
        } else if (Long.class.equals(clz)) {
            return node.asLong();
        } else if (Date.class.equals(clz)) {
            return new Date(node.asLong());
        } else {
            logger.warn("Data-Smart：User对象反序列化时有未处理的类型{}", clz.getName());
            return null;
        }
    }
}
